# core/scanner/parallel_scanner.py
import concurrent.futures
from functools import lru_cache

class ParallelScanner:
    def __init__(self, max_workers=4):
        self.executor = concurrent.futures.ThreadPoolExecutor(max_workers)
        self.file_queue = PriorityQueue()  # 按格式优先级排序
        
    @lru_cache(maxsize=1000)
    def _parse_metadata(self, file_path):
        # 使用with确保文件句柄释放
        with open(file_path, 'rb') as f:
            header = f.read(16)
            if header.startswith(b'DSD'):
                return self._parse_dsd(f)
            # 其他格式处理...

    async def scan_directory(self, path):
        futures = []
        for root, _, files in os.walk(path):
            for file in sorted(files, key=lambda x: x.split('.')[-1]):
                future = self.executor.submit(
                    self._safe_process, 
                    os.path.join(root, file)
                )
                futures.append(future)
                
        return await asyncio.gather(*futures)

    def _safe_process(self, file_path):
        try:
            return self._parse_metadata(file_path)
        except Exception as e:
            self._log_error(file_path, e)
            return None